﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Sicurezza.Entita;
using OpenSSL.X509;
using OpenSSL.Core;

namespace Sicurezza.Client.Manager
{
    public class RequestManager
    {

        public static List<Pair> GetAll()
        {
            string[] paths = FileManager.GetRequests();
            List<Pair> elements = new List<Pair>();
            Pair p = null;
            X509Request r = null;
            for (int i = 0; i < paths.Length; i++)
            {
                p = new Pair();
                p.key = paths[i];
                r = new X509Request(FileManager.LoadRequest(paths[i]));
                p.value = r.Subject.ToString();
                elements.Add(p);
            }

            return elements;
        }

        public static string Check(string ReqId)
        {
            string cert = WSManager.GetCertificate(ReqId);
            if (!string.IsNullOrEmpty(cert))
            {
                X509Certificate c;
                try
                {
                    c = new X509Certificate(new BIO(cert));


                    int serial = c.SerialNumber;
                    FileManager.MovePrivateKey(ReqId, serial);
                    FileManager.DeleteRequest(ReqId);
                    X509Manager.Save(c);
                }
                catch (OpenSslException ex) 
                {
                    FileManager.RejectRequest(ReqId);
                    throw new ManagerException(cert);
                }

            }
            return cert;
        }

        public static string Send(string request)
        {
            return WSManager.SendRequest(request);
        }

        public static X509Request Get(string ReqId)
        {
            return new X509Request(FileManager.LoadRequest(ReqId));
        }
    }
}
